package top.choviwu.shortUrl.web;


import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import top.choviwu.shortUrl.util.JsonUtils;
import top.choviwu.shortUrl.util.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Slf4j
@Controller
public class GenUrlController {


    @GetMapping(value = "/{key}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object redirect(@PathVariable String key, HttpServletResponse response) throws IOException {
        if (!StringUtils.judgeStr(key, 7)) {
            log.info(">>>>>>>>>>>url less 7");
            return "redirect:https://choviwu.top";
        }

        HttpResponse response1 = HttpUtil.createGet("https://choviwu.top/getOriginUrl?key=" + key).execute();
        System.out.println(response1.body());
        if (!response1.isOk()) {
            log.info(">>>>>>>>>>>url response fail");
            return "redirect:https://choviwu.top";
        }
        try {
            ApiResponse apiResponse = JsonUtils.toBean(response1.body(), ApiResponse.class);
            if (!Objects.equals(200, apiResponse.getCode())) {
                log.info(">>>>>>>>>>>url response code not equals 200 ");
                return "redirect:https://choviwu.top";
            }
            return "redirect:" + apiResponse.getData();
        } catch (Exception e) {
            e.printStackTrace();
            return "redirect:https://choviwu.top";
        }
    }
}
